<?php

namespace app\admin\service;

use app\admin\validate\AdminRoleValidate;
use support\spark\exception\ApiException;
use support\spark\model\system\AdminRole;
use support\spark\model\system\AdminUser;

class RoleService
{
    /**
     * 获取角色列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $name = $param['name'];

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $adminRoleModel = new AdminRole();
        $list = $adminRoleModel->getPaginateList($where, ['*'], ['id' => 'desc'], [], $limit);
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加角色
     * @param $param
     * @return array
     */
    public function addRole($param)
    {
        // 检验完整性
        $validate = new AdminRoleValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $adminRoleModel = new AdminRole();
        $has = $adminRoleModel->checkUnique([
            'name' => $param['name']
        ]);
        if (!empty($has)) {
            throw  new  ApiException('该角色已经存在', -1);
        }
        $param['role_node'] = '122,123,126,' . $param['role_node'];
        $param['create_time'] = now();
        $param['update_time'] = now();
        $adminRoleModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑角色
     * @param $param
     * @return array
     */
    public function editRole($param)
    {
        // 检验完整性
        $validate = new AdminRoleValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $adminRoleModel = new AdminRole();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $adminRoleModel->checkUnique($where);
        if (!empty($has)) {
            throw  new  ApiException('该角色已经存在', -1);
        }
        $adminRoleModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }

    /**
     * 删除角色
     * @param $id
     * @return array
     */
    public function delRole($id)
    {
        $adminUserModel = new AdminUser();
        $has = $adminUserModel->getInfoByWhere([
            'role_id' => $id
        ], ['id']);
        if (!empty($has)) {
            throw  new  ApiException('该角色已被使用无法删除', -1);
        }
        $adminRoleModel = new AdminRole();
        $adminRoleModel->delById($id);
        return dataReturn(0, '删除成功');
    }

}